//
//  GIFEditorViewController.swift
//  GifUsage
//
//  Created by han on 2020/12/21.
//  Copyright © 2020 Ting Han. All rights reserved.
//

import UIKit
import Photos
import AVFoundation

class GIFEditorViewController: UIViewController {
    
    @IBOutlet weak var containerView: UIView!
    @IBOutlet weak var slider: UISlider!
    
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var playButton: UIButton!
    @IBOutlet weak var reverseButton: UIButton!
    @IBOutlet weak var scaleButton: UIButton!
    @IBOutlet weak var filterButton: UIButton!
    @IBOutlet weak var textButton: UIButton!
    
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
    let activityIndicator = UIActivityIndicatorView(style: .large)
    
    var assets = [PHAsset]()
    var images = [ImageModel]()
    
    var videoAsset: PHAsset?
    var videoURLAsset: AVURLAsset?
    
    // 1s 10帧
    let timeScale = 10
    
    
    @IBOutlet weak var durationLabel: UILabel!
    
    var imagePlayer: ImagePlayer!
    override func viewDidLoad() {
        super.viewDidLoad()
        commonInit()
    }
    
    @IBAction func sliderValueChanged(_ sender: Any) {
        imagePlayer.defaultDuration = duration
        durationLabel.text = String(format: "%.3f", duration)
    }
    @IBAction func playAction(_ sender: Any) {
        
    }
    @IBAction func reverseAction(_ sender: Any) {
    }
    @IBAction func scaleAction(_ sender: Any) {
    }
    @IBAction func filterAction(_ sender: Any) {
    }
    @IBAction func textAction(_ sender: Any) {
    }
    
    
    @IBAction func generateGIFAction(_ sender: Any) {
        generateGIF()
    }
    
    @IBAction func gridAtion(_ sender: Any) {
        let image = ImageGridViewController()
        image.dataSource = images.map { $0.image }
        navigationController?.pushViewController(image, animated: true)
    }
    
    
    var duration: TimeInterval {
        TimeInterval(slider.value)
    }
}

extension GIFEditorViewController {
    private func commonInit() {
        imagePlayer = ImagePlayer(containerView: imageView)
        view.addSubview(activityIndicator)
        activityIndicator.center = CGPoint(x: view.frame.midX, y: view.frame.midY)
        loadImagesFromImageAssets()
        loadVideoData()
    }
    
    func loadImagesFromImageAssets() {
        guard assets.count > 0 else { return }
        slider.value = 0.3
        imagePlayer.defaultDuration = duration
        durationLabel.text = String(format: "%.3f", duration)
        
        DispatchQueue.global().async {
            self.images.removeAll()
            let options = PHImageRequestOptions()
            options.resizeMode = .none
            options.deliveryMode = .highQualityFormat
            options.isNetworkAccessAllowed = true
            for asset in self.assets {
                let size = CGSize(width: asset.pixelWidth, height: asset.pixelHeight)
                PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFit, options: options, resultHandler: { image, _ in
                    guard let image = image else { return }
                    self.images.append(ImageModel(image: image, duration: nil))
                    
                    if self.images.count >= self.assets.count {
                        self.imagePlayer.images = self.images
                        DispatchQueue.main.async {
                            self.imagePlayer.play()
                            self.navigationItem.title = "\(self.images.count)帧"
                        }
                    }
                })
            }
        }
    }
    
    func loadVideoImages() {
        guard let videoURLAsset = videoURLAsset else { return }
        images.removeAll()
        
        VideoTools.fetchFrames(urlAsset: videoURLAsset, timeScale: CMTimeScale(timeScale)) { (image, result) in
            if let image = image {
                self.images.append(ImageModel(image: image, duration: nil))
            }
            
            if result {
                self.imagePlayer.images = self.images
                DispatchQueue.main.async {
                    self.imagePlayer.play()
                    self.navigationItem.title = "\(self.images.count)帧"
                }
            }
        }
    }
    
    func loadVideoData() {
        guard let videoAsset = videoAsset else { return }
        slider.value = 1 / Float(timeScale)
        imagePlayer.defaultDuration = duration
        durationLabel.text = String(format: "%.3f", duration)
        
        let options = PHVideoRequestOptions()
        options.isNetworkAccessAllowed = true
        options.version = .original
        
        PHImageManager.default().requestAVAsset(forVideo: videoAsset, options: options) { (avAsset, audioMix, info) in
            if avAsset?.isKind(of: AVURLAsset.self) == true {
                self.videoURLAsset = avAsset as? AVURLAsset
                self.loadVideoImages()
            }
        }
    }

    func generateGIF() {
      
        let display = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "GIFDisplayViewController") as! GIFDisplayViewController
        display.images = images
        display.duration = duration
        navigationController?.pushViewController(display, animated: true)
    }
}

extension GIFEditorViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(type(of: ThumnailCell.self))", for: indexPath) as! ThumnailCell
        return cell
    }
}

class ThumnailCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView!
}
